import csv


def check_utf8_csv_and_preview(file_path, preview_rows=5):
    try:
        # 尝试以UTF-8编码打开并读取CSV文件
        with open(file_path, 'r', encoding='utf-8') as csv_file:
            reader = csv.reader(csv_file)

            # 读取前几行数据
            rows = []
            for i, row in enumerate(reader):
                if i < preview_rows:
                    rows.append(row)
                else:
                    break

        print(f"✅ 文件 {file_path} 完全使用UTF-8编码。")
        print(f"\n文件前{preview_rows}行内容：")
        for i, row in enumerate(rows, 1):
            print(f"第{i}行: {row}")

        return True

    except UnicodeDecodeError as e:
        print(f"❌ 文件 {file_path} 包含非UTF-8字符。")
        print(f"错误详情: {str(e)}")
        return False
    except FileNotFoundError:
        print(f"❌ 文件 {file_path} 不存在。")
        return False
    except Exception as e:
        print(f"❌ 处理文件时发生错误: {str(e)}")
        return False


# 替换为你的CSV文件路径
csv_file_path = r"D:\competition\2026quanqiu\cons\pred_results_web400.csv"
check_utf8_csv_and_preview(csv_file_path)
